package com.yyplatform.admin.platform.generator.helper;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.yyplatform.admin.platform.generator.model.ColumnVO;
import com.yyplatform.admin.platform.generator.model.TableVO;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class MySQLSchemaHelper {


    private JdbcTemplate jdbcTemplate;

    public List<TableVO> listTable() {
        String sql = " SELECT* FROM information_schema.`TABLES` WHERE  TABLE_SCHEMA = 'yyplatform'";


        return jdbcTemplate.queryForStream(sql, (rs, rowNum) -> {
            TableVO tableVO = new TableVO();

            tableVO.setTableSchema(rs.getString("TABLE_SCHEMA"));
            tableVO.setTableName(rs.getString("TABLE_NAME"));
            tableVO.setTableComment(rs.getString("TABLE_COMMENT"));

            return tableVO;
        }).collect(Collectors.toList());
    }


    public List<ColumnVO> listColumn(String tableName) {
        String sql = "SELECT  *  FROM  information_schema.`COLUMNS`"
                + " WHERE TABLE_NAME = '" + tableName + "' AND TABLE_SCHEMA = 'yyplatform'";


        return jdbcTemplate.queryForStream(sql, (rs, rowNum) -> {
            ColumnVO columnVO = new ColumnVO();

            columnVO.setColumnComment(rs.getString("COLUMN_COMMENT"));
            columnVO.setColumnDefault(rs.getString("COLUMN_DEFAULT"));
            columnVO.setColumnKey(rs.getString("COLUMN_KEY"));
            columnVO.setColumnName(rs.getString("COLUMN_NAME"));
            columnVO.setColumnType(rs.getString("COLUMN_TYPE"));
            columnVO.setDataType(rs.getString("DATA_TYPE"));
            columnVO.setIsNullable(rs.getString("IS_NULLABLE"));
            columnVO.setExtra(rs.getString("EXTRA"));

            columnVO.setCharacterMaximumLength(rs.getLong("CHARACTER_MAXIMUM_LENGTH"));
            columnVO.setCharacterOctetLength(rs.getLong("CHARACTER_OCTET_LENGTH"));
            columnVO.setNumericPrecision(rs.getLong("NUMERIC_PRECISION"));
            columnVO.setNumericScale(rs.getLong("NUMERIC_SCALE"));


            return columnVO;

        }).collect(Collectors.toList());
    }


}
